package py.com.sole.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import py.com.sole.dao.MateriaDao;
import py.com.sole.dao.DaoFactory;

import py.com.sole.model.Materia;

public class MateriaImpl implements MateriaDao {

  EntityManager em = DaoFactory.getEm();

  @Override
  public Materia addMateria(Materia materia) {

    try {
      em.getTransaction().begin();
      em.persist(materia);
      em.getTransaction().commit();
      return materia;
    } catch (Exception e) {
      //System.out.println("Error al intentar persistir "+e);
      e.printStackTrace();
      return null;
    }

  }

  @Override
  public void deleteMateria(int id) {
    try {
      em.getTransaction().begin();
      em.remove(this.getMateriaById(id));
      em.getTransaction().commit();

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public void updateMateria(Materia materia) {
    // TODO Auto-generated method stub
    try {
      em.getTransaction().begin();
      em.merge(this.getMateriaById(materia.getId()));
      em.getTransaction().commit();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @SuppressWarnings("all")
  @Override
  public List<Materia> getMaterias() {
    return em.createQuery("SELECT m FROM Materia m where m.activo=TRUE").getResultList();
  }

  @Override
  public Materia getMateriaById(int id) {
    return (Materia) em.createQuery("SELECT m FROM Materia m where m.id = " + id).getSingleResult();
  }

  @Override
  public Materia getMateriaByName(String value) {
    // TODO Auto-generated method stub
    try {
      Query q = em.createNamedQuery("Materia.findByDescripcion");
      q.setParameter("descripcion", value);
      return (Materia) q.getSingleResult();
    } catch (Exception e) {
      return null;
    }

  }

}
